﻿<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="urlwatcher" %>

<%
    //
    //read configuration and init variables
    //
    string response = "failed";
    byte[] secretKey = null;
    ASCIIEncoding textConverter = new ASCIIEncoding();
    string sSharedSecret = WebConfigurationManager.AppSettings["urlwatcher-shared-secret"];
    secretKey = textConverter.GetBytes(sSharedSecret);
    string sAuthTokenName = WebConfigurationManager.AppSettings["urlwatcher-authorization-token"];
    string sAuthParamName = WebConfigurationManager.AppSettings["urlwatcher-authorization-parameter"];
    string sTargetUrlName = WebConfigurationManager.AppSettings["urlwatcher-target-url-parameter"];
    string sAuthTokenLife = WebConfigurationManager.AppSettings["urlwatcher-authorization-time"];
    long lAuthTime = long.Parse(sAuthTokenLife);
    //
    //handle request
    //
    string authToken = Request.QueryString[sAuthTokenName];
    string authParam = Request.QueryString[sAuthParamName];
    if (null == authToken || "".Equals(authToken))
    {//if the auth. token is not present we failed
        response = "failed";
    }
    else
    {
        byte[] encrypted = System.Convert.FromBase64String(authToken);
        byte[] fromEncrypted = TokenUtils.decryptECB(secretKey, PaddingMode.ISO10126, encrypted);
        string decryptedToken = textConverter.GetString(fromEncrypted);
        string sTokenAppId = TokenUtils.parseValue(sAuthParamName, decryptedToken);
        string sDateTime = TokenUtils.parseValue("time", decryptedToken);
        if ("".Equals(sDateTime) || "".Equals(sTokenAppId)) { response = "failed"; }
        else
        {
            DateTime datetime = DateTime.Parse(sDateTime);
            long timediff = (DateTime.Now.Ticks - datetime.Ticks) / 10000000;
            if (timediff > lAuthTime) { response = "failed"; }
            else
            {
                if (!sTokenAppId.Equals(authParam)) { response = "failed"; }
                else { response = "approved"; }
            }
        }
    }
    // encrypt response
    byte[] responseData = TokenUtils.encryptECB(secretKey, PaddingMode.ISO10126, textConverter.GetBytes(response));
    string encryptedResponse = System.Convert.ToBase64String(responseData);

    Response.Write(encryptedResponse);
%>
